|
1
|
|
|
import { handleActions } from 'redux-actions'; |
|
2
|
|
|
import { pipe, isEmpty, assoc, map, prop } from 'ramda'; |
|
3
|
|
|
import { v4 as uuid } from 'uuid'; |
|
4
|
|
|
import { homepage } from '../../../package.json'; |
|
5
|
|
|
|
|
6
|
|
|
/* eslint-disable padding-line-between-statements */ |
|
7
|
1 |
|
export const FETCH_SERVERS_START = 'shlink/servers/FETCH_SERVERS_START'; |
|
8
|
1 |
|
export const FETCH_SERVERS = 'shlink/servers/FETCH_SERVERS'; |
|
9
|
|
|
/* eslint-enable padding-line-between-statements */ |
|
10
|
|
|
|
|
11
|
1 |
|
const initialState = { |
|
12
|
|
|
list: {}, |
|
13
|
|
|
loading: false, |
|
14
|
|
|
}; |
|
15
|
|
|
|
|
16
|
2 |
|
const assocId = (server) => assoc('id', server.id || uuid(), server); |
|
17
|
|
|
|
|
18
|
|
|
export default handleActions({ |
|
19
|
|
|
[FETCH_SERVERS_START]: (state) => ({ ...state, loading: true }), |
|
20
|
1 |
|
[FETCH_SERVERS]: (state, { list }) => ({ list, loading: false }), |
|
21
|
|
|
}, initialState); |
|
22
|
|
|
|
|
23
|
2 |
|
export const listServers = ({ listServers, createServers }, { get }) => () => async (dispatch) => { |
|
24
|
2 |
|
dispatch({ type: FETCH_SERVERS_START }); |
|
25
|
2 |
|
const localList = listServers(); |
|
26
|
|
|
|
|
27
|
2 |
|
if (!isEmpty(localList)) { |
|
28
|
1 |
|
dispatch({ type: FETCH_SERVERS, list: localList }); |
|
29
|
|
|
|
|
30
|
1 |
|
return; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
// If local list is empty, try to fetch it remotely and calculate IDs for every server |
|
34
|
1 |
|
const remoteList = await get(`${homepage}/servers.json`) |
|
35
|
|
|
.then(prop('data')) |
|
36
|
|
|
.then(map(assocId)) |
|
37
|
|
|
.catch(() => []); |
|
38
|
|
|
|
|
39
|
1 |
|
createServers(remoteList); |
|
40
|
1 |
|
dispatch({ type: FETCH_SERVERS, list: remoteList.reduce((map, server) => ({ ...map, [server.id]: server }), {}) }); |
|
41
|
|
|
}; |
|
42
|
|
|
|
|
43
|
1 |
|
export const createServer = ({ createServer }, listServersAction) => pipe(createServer, listServersAction); |
|
44
|
|
|
|
|
45
|
1 |
|
export const deleteServer = ({ deleteServer }, listServersAction) => pipe(deleteServer, listServersAction); |
|
46
|
|
|
|
|
47
|
1 |
|
export const createServers = ({ createServers }, listServersAction) => pipe( |
|
48
|
|
|
map(assocId), |
|
49
|
|
|
createServers, |
|
50
|
|
|
listServersAction |
|
51
|
|
|
); |
|
52
|
|
|
|